var express = require('express');
var router = express.Router();
const fs = require('fs');

const screenshotTools = require('../scripts/node-screenshots-tools');

const imageDirectory = './public/images';

async function getImageName() {
  const now = new Date();
  const subDir = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;

  const targetDirectory = `${imageDirectory}/${subDir}`;

  if (!fs.existsSync(targetDirectory)) {
    await fs.mkdir(targetDirectory, (error) => {
      if (error) {
        console.log(error);
      }
    });
  }
  return `${targetDirectory}/${now.getHours().toString().padStart(2, '0')}-${now.getMinutes().toString().padStart(2, '0')}-${now.getSeconds().toString().padStart(2, '0')}-${now.getMilliseconds().toString().padStart(3, '0')}.jpeg`;
}

const captureScreenshot = async () => {
  const imageName = await getImageName();
  await screenshotTools.captureMonitor(imageName);
  return imageName;
}


/* GET home page. */
router.get('/', async (_req, res) => {
  var imageURL = await captureScreenshot();
  res.render('index', { title: 'Screenshot Web: To get the latest screenshot by clicking Recapture button.', imageURL: imageURL });
});

router.get('/screenshot', async function (_req, res) {
  var imageURL = await captureScreenshot();
  res.send(imageURL)
});

router.get('/data', async function (req, res) {
  const imageName = await getImageName();
  const data = await screenshotTools.captureAppChrome(imageName);
  res.set('Content-Type', 'image/jpeg');
  res.send(data);
})

setInterval(captureScreenshot, 60000);

module.exports = router;

